﻿using System;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using System.Diagnostics;

namespace Ahmad.A.Ousman.WindowsProxy.Common
{
    public static class Extensions
    {
        public static void Log(this Exception exception, String source)
        {
            Utility.Log(source, exception.Message, EventLogEntryType.Error);
            Utility.Log(source, exception.StackTrace, EventLogEntryType.Error);
        }

        public static string SerializeObjectToXml<T>(this T toSerialize)
        {
            var serializer = new XmlSerializer(typeof(T));
            var sb = new StringBuilder();
            using (var writer = new StringWriter(sb))
            {
                serializer.Serialize(writer, toSerialize);
            }
            return sb.ToString();
        }

        public static T DeserializeXmlToObject<T>(this string xml)
        {
            var serializer = new XmlSerializer(typeof(T));
            using (var reader = new StringReader(xml))
            {
                return (T)serializer.Deserialize(reader);
            }
        }

        public static void Clone<T>(this T a, T b)
        {
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (property.CanWrite)
                {
                    property.SetValue(a, property.GetValue(b, null), null);
                }
            }
        }
    }
}
